package com.runen.infinitemovement.widget.popupwind;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.king.zxing.util.CodeUtils;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.PathSectionCompleteEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.ShareBitmapUtils;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class SharePoppupWindow extends PopupWindow {
    private TextView tv_dismiss;
    private LinearLayout ll_share_wechat, ll_share_friend, ll_share_qq, ll_share_qqzone, ll_save_pic, ll_picture;
    private RelativeLayout rl_picture;
    private Context context;
    private View layout;
    private String describe;
    private int type = 0; //0:运动数据分享   1：邀请好友分享  2：打卡分享;3:我的长征路路段完成分享
    private String title;
    private String imageUrl;
    private OnClick onClick;
    private Bitmap bitmap;
    private String imagePath;//图片地址
    private TextView tv_rank, tv_start_end_name, tv_hozom, tv_name, tv_days, tv_miles;
    private ImageView iv_code;
    private RoundedCornersImage rci_header;

    private PathSectionCompleteEntity.DataBean entity;//当type=3 才有值

    public void setOnClick(OnClick onClick) {
        this.onClick = onClick;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    /**
     * 我的长征路  路段完成弹框
     *
     * @param context
     * @return
     */
    public static SharePoppupWindow getInstance(Context context, int type, PathSectionCompleteEntity.DataBean entity) {
        return new SharePoppupWindow(context, type, entity);
    }

    public static SharePoppupWindow getInstance(Context context) {
        return new SharePoppupWindow(context, 2, null);
    }

    public static SharePoppupWindow getInstance(Context context, String title, String describe, String imageUrl) {
        return new SharePoppupWindow(context, title, describe, imageUrl, 0);
    }

    public static SharePoppupWindow getInstance(Context context, String title, String describe, String imageUrl, int type) {
        return new SharePoppupWindow(context, title, describe, imageUrl, type);
    }

    private SharePoppupWindow(Context context, int type, PathSectionCompleteEntity.DataBean entity) {
        super(context);
        this.context = context;
        this.type = type;
        this.entity = entity;
        initView();
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //this.setHeight((int) (CommonUtil.getScreenHW((Activity) context)[1] / 3));
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        // 这样设置才能点击屏幕外dismiss窗口
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(layout);

        initEvent();
    }

    private SharePoppupWindow(Context context, String title, String describe, String imageUrl, int type) {
        super(context);
        this.context = context;
        this.describe = describe;
        this.type = type;
        this.title = title;
        this.imageUrl = imageUrl;
        initView();
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //this.setHeight((int) (CommonUtil.getScreenHW((Activity) context)[1] / 3));
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        // 这样设置才能点击屏幕外dismiss窗口
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(layout);

        initEvent();
    }


    private void initView() {
        layout = View.inflate(context, R.layout.popup_share_info, null);
        tv_dismiss = layout.findViewById(R.id.tv_dismiss);

        ll_share_wechat = layout.findViewById(R.id.ll_share_wechat);

        ll_share_friend = layout.findViewById(R.id.ll_share_friend);

        ll_share_qq = layout.findViewById(R.id.ll_share_qq);

        ll_share_qqzone = layout.findViewById(R.id.ll_share_qqzone);

        ll_save_pic = layout.findViewById(R.id.ll_save_pic);
        rl_picture = layout.findViewById(R.id.rl_picture);

        ll_save_pic.setVisibility(View.GONE);
        rl_picture.setVisibility(View.GONE);
        if (type == 1) {
            ll_share_qq.setVisibility(View.GONE);
            ll_share_qqzone.setVisibility(View.GONE);
        } else if (type == 2) {
            ll_share_qqzone.setVisibility(View.GONE);
            ll_save_pic.setVisibility(View.VISIBLE);
            if (Build.VERSION.SDK_INT >= 30) {
                ll_share_qq.setVisibility(View.GONE);
            } else {
                ll_share_qq.setVisibility(View.VISIBLE);
            }
        } else if (type == 3) {
            ll_share_qqzone.setVisibility(View.GONE);
            ll_save_pic.setVisibility(View.VISIBLE);
            if (Build.VERSION.SDK_INT >= 30) {
                ll_share_qq.setVisibility(View.GONE);
            } else {
                ll_share_qq.setVisibility(View.VISIBLE);
            }
            rl_picture.setVisibility(View.VISIBLE);
            if (entity != null) {
                tv_rank = layout.findViewById(R.id.tv_rank);
                tv_start_end_name = layout.findViewById(R.id.tv_start_end_name);
                tv_hozom = layout.findViewById(R.id.tv_hozom);
                rci_header = layout.findViewById(R.id.rci_header);
                tv_name = layout.findViewById(R.id.tv_name);
                tv_days = layout.findViewById(R.id.tv_days);
                tv_miles = layout.findViewById(R.id.tv_miles);
                iv_code = layout.findViewById(R.id.iv_code);
                ll_picture = layout.findViewById(R.id.ll_picture);

                tv_rank.setText(entity.myRank + "");
                String startEndName = "完成 <font color='#B7232B'>%s-%s<font/> 路段的人";
                tv_start_end_name.setText(Html.fromHtml(String.format(startEndName, entity.startPoint, entity.endPoint)));
                String huozom = "获得火种：%s颗";
                tv_hozom.setText(String.format(huozom, entity.tinderNumber));

                String url = String.format(Constant.INVIT_FRIEND, UserAPI.getUserId());
                iv_code.setImageBitmap(CodeUtils.createQRCode(url, 600));
                if (!TextUtils.isEmpty(entity.headImgUrl)) {
                    Glide.with(context).load(entity.headImgUrl)
                            .into(new SimpleTarget<Drawable>() {
                                @Override
                                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                                    rci_header.setImageDrawable(resource);
                                    bitmap = ShareBitmapUtils.savePoster((Activity) context, ll_picture);
                                }
                            });
                }
                tv_days.setText(entity.day + "");
                tv_miles.setText(CommonUtil.Double2position(entity.mileage) + "");
                tv_name.setText(entity.nickname);
                if (tv_name.getText().toString().length() > 6) {
                    tv_name.setText(tv_name.getText().toString().substring(0, 6) + "...");
                }

                bitmap = ShareBitmapUtils.savePoster((Activity) context, ll_picture);
            }
        }
    }

    private void initEvent() {
        //关闭Dialog
        tv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                if (onClick != null)
                    onClick.dismiss();
            }
        });
        ll_share_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare(Wechat.NAME);
                if (onClick != null) {
                    onClick.hitCard();
                }
                if (type != 3)
                    dismiss();
            }
        });
        ll_share_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare(WechatMoments.NAME);
                if (onClick != null) {
                    onClick.hitCard();
                }
                if (type != 3)
                    dismiss();
            }
        });
        ll_share_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onClick != null && bitmap != null) {
                    onClick.hitCard();
                    imagePath = onClick.imagePath(bitmap);
                    if (type == 3) {
                        imagePath = ShareBitmapUtils.saveToLocal(context, bitmap);
                    }
                }
                showShare(QQ.NAME);
                if (type != 3)
                    dismiss();
            }
        });
        ll_share_qqzone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare(QZone.NAME);
                if (onClick != null) {
                    onClick.hitCard();
                }
                if (type != 3)
                    dismiss();
            }
        });
        ll_save_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onClick != null && bitmap != null) {
                    onClick.savePic(bitmap);
                    if (type != 3)
                        dismiss();
                    else
                        imagePath = ShareBitmapUtils.saveToLocal(context, bitmap);
                }
            }
        });
    }


    private void showShare(String platform) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(describe);
        if (type == 2 || type == 3) {
            sp.setImageData(bitmap);
            sp.setShareType(Platform.SHARE_IMAGE);
            sp.setImagePath(imagePath);
        } else {
            sp.setSite(imageUrl);
            sp.setSiteUrl(imageUrl);
        }
        if (platform.contains("Wechat")) {
//            LogUtil.e("imageUrl", imageUrl);
            // url仅在微信（包括好友和朋友圈）中使用
            if (type != 2 && type != 3) {
                sp.setUrl(imageUrl);
                sp.setShareType(Platform.SHARE_WEBPAGE);
            }
        } else {
            // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
            if (!TextUtils.isEmpty(imageUrl))
                sp.setTitleUrl(imageUrl);
        }
        Platform pf = ShareSDK.getPlatform(platform);
// 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
        pf.setPlatformActionListener(new PlatformActionListener() {
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
                int a = 0;
            }

            public void onComplete(Platform arg0, int arg1, HashMap arg2) {
                //分享成功的回调
                int a = 0;
            }

            public void onCancel(Platform arg0, int arg1) {
                //取消分享的回调
                int a = 0;
            }
        });
        // 执行图文分享
        pf.share(sp);


//        OnekeyShare oks = new OnekeyShare();
//        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
//        if (platform != null) {
//            oks.setPlatform(platform);
//        }
//        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(title);
//        // text是分享文本，所有平台都需要这个字段
//        oks.setText(describe);
//        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
////        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
//        if (platform.contains("Wechat")) {
//            // url仅在微信（包括好友和朋友圈）中使用
//            oks.setUrl(imageUrl);
//        } else {
//            // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
//            oks.setTitleUrl(imageUrl);
//        }
//        //启动分享
//        oks.show(MobSDK.getContext());
    }

    public void show(float alpha) {
        //        this.setAnimationStyle(R.style.Animation);
        //防止部分手机底部状态栏与popupWindow重叠
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.setAnimationStyle(R.style.AnimationBottomFade);
        //popupWindow底部显示
        this.showAtLocation(((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();

        lp.alpha = alpha;
        if (lp.alpha == 1) {
            ((Activity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        ((Activity) context).getWindow().setAttributes(lp);
    }

    public void show() {
        show(0.5f);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = 1.0f;
        ((Activity) context).getWindow().setAttributes(lp);
    }

    public interface OnClick {
        void savePic(Bitmap bitmap);

        void hitCard();

        void dismiss();

        String imagePath(Bitmap bitmap);
    }

}
